package com.jsz.peini.common.util;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;

/**
 * @author Han Guohong
 * @version 2017-2-6 上午10:58:17
 * 类说明
 */
public class UploadQN {
	private static final Logger logger = LoggerFactory.getLogger(UploadQN.class);
	
	//设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "ob_Srv3WdQDLxFHuJiC6zzn-lJ8YmVBK2G6TH9BZ";
    String SECRET_KEY = "H-JOZJDWIDnP-1fy81uIVdUfGUgmaNBrhaJtsGaf";
    //要上传的空间
    String bucketname = "jinshouzhipn";
    //上传到七牛后保存的文件名
    String key = "fsfg.jpg";
    //上传文件的路径
    String FilePath = "E:/tomcat7-2/webapps/uploadFiles/upload/userimage/2017/1/21/5d5f890aa9e946b5992a9521ad4bd821.jpg";

    //设置转码的队列（"test1是刚刚设置的队列名称"）  
    String pipeline = "pnshuiyin";    
  
    //------------------图片水印(水印样式来源于mybucket中的sy1样式)-------------------  
	String fops = "watermark/1/image/aHR0cDovL29reG00YzJnZy5ia3QuY2xvdWRkbi5jb20vaWNvbi5wbmc=/dissolve/59/gravity/SouthEast/dx/10/dy/10" ;  
  
    //可以对转码后的文件进行使用saveas参数自定义命名，当然也可以不指定文件会默认命名并保存在当前空间。  
   //saveBucket+":"+saveKey  
    String urlbase64 = UrlSafeBase64.encodeToString(bucketname+":"+key);    //bucketname为空间的名称，key为保存的文件名称  
    String pfops = fops +"|saveas/"+ urlbase64;  
    
    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    
    ///////////////////////指定上传的Zone的信息//////////////////
    //第一种方式: 指定具体的要上传的zone
    //注：该具体指定的方式和以下自动识别的方式选择其一即可
    //要上传的空间(bucket)的存储区域为华东时
    // Zone z = Zone.zone0();
    //要上传的空间(bucket)的存储区域为华北时
    Zone z = Zone.zone1();
    //要上传的空间(bucket)的存储区域为华南时
    // Zone z = Zone.zone2();

    //第二种方式: 自动识别要上传的空间(bucket)的存储区域是华东、华北、华南。
    //Zone z = Zone.autoZone();
    Configuration c = new Configuration(z);

    //创建上传对象
    UploadManager uploadManager = new UploadManager(c);
    
    BucketManager bucketManager = new BucketManager(auth, c);

    public static void main(String args[]) throws IOException {
        //new UploadQN().upload();
    }

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        //return auth.uploadToken(bucketname);
    	return auth.uploadToken(bucketname,null,3600,new StringMap()  
		        .putNotEmpty("persistentOps", pfops)  
		        .putNotEmpty("persistentPipeline", pipeline), true);
    }

    public void upload(MultipartFile file,String key) throws IOException {
        try {
            //调用put方法上传
            Response res = uploadManager.put(file.getBytes(), key, getUpToken());
            //打印返回的信息
            //logger.info(res.bodyString());
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            //logger.info(r.toString());
            try {
                //响应的文本信息
                logger.info(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
    }
    
    public void upload(byte [] file,String key) throws IOException {
        try {
            //调用put方法上传
            Response res = uploadManager.put(file, key, getUpToken());
            //打印返回的信息
            logger.info(res.bodyString());
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            //logger.info(r.toString());
            try {
                //响应的文本信息
                logger.info(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
    }
    
    public void delete(String url){
    	try {
    	    //单次批量请求的文件数量不得超过1000
    	    String[] keyList = new String[]{url};
    	    BucketManager.Batch batchOperations = new BucketManager.Batch();
    	    batchOperations.delete(bucketname, keyList);
    	    Response response = bucketManager.batch(batchOperations);
    	    BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
    	    for (int i = 0; i < keyList.length; i++) {
    	        BatchStatus status = batchStatusList[i];
    	        String key = keyList[i];
    	        logger.info(key + "\t");
    	        if (status.code == 200) {
    	            logger.info("delete success");
    	        } else {
    	            logger.info("error");
    	        }
    	    }
    	} catch (QiniuException ex) {
    	    System.err.println(ex.response.toString());
    	}
    }
}
